# Python实战编程:从零学Python 黑马程序员 编著
# 创建时间:2021/1/29 下午 12:57
import datetime

from io import BytesIO

from django.db.models import Q, Max
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect


from utils.image_code import check_code
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm, GregisterForm


def register(request):
    """ 注册 """
    if request.method == 'GET':
        form = RegisterModelForm()

        return render(request, 'web/register.html', {'form': form})

    form = RegisterModelForm(data=request.POST)
    try:
        print(form)
    except Exception as erro:
         print(erro)

    print(form.is_valid())
    if form.is_valid():
        # 验证通过，写入数据库（密码要是密文）
        # instance = form.save，在数据库中新增一条数据，并将新增的这条数据赋值给instance

        # 用户表中新建一条数据（注册）
        instance = form.save()

        # 方式二
        mobile_phone = form.cleaned_data['mobile_phone']
        org_id = form.cleaned_data['org_id']

        # 把用户名写入到session中
        user_object = models.organization.objects.filter(mobile_phone=mobile_phone).first()
        request.session['user_mobile_phone'] = user_object.mobile_phone
        request.session.set_expiry(60 * 60 * 24 * 14)

        v = models.trade.objects.filter(org_id=user_object.org_id).filter(status="2").order_by(
            "-crdate").first()

        if v:  # 查询到了有订单
            if v.end >= datetime.datetime.now():  # 一个有没有时区一个有时区不能比较
                return JsonResponse({"status": True, 'data': "/web/index/"})
            else:
                return JsonResponse({"status": True, 'data': "/web/price/"})
        else:  # 没买过去
            return JsonResponse({"status": True, 'data': "/web/price/"})
    return JsonResponse({'status': False, 'error': form.errors})


def Gregister(request):
    """ 注册 """
    if request.method == 'GET':
        form = GregisterForm()

        return render(request, 'web/Gregister.html', {'form': form})

    form = GregisterForm(data=request.POST)
    try:
        print(form)
    except Exception as erro:
        print(erro)

    print(form.is_valid())
    if form.is_valid():
        # 验证通过，写入数据库（密码要是密文）
        # instance = form.save，在数据库中新增一条数据，并将新增的这条数据赋值给instance

        # 用户表中新建一条数据（注册）


        # 方式二


        username=form.cleaned_data['username']


        mobile_phone = form.cleaned_data['mobile_phone']


        invite=form.cleaned_data["invite"]

        invite_object = models.invite.objects.filter(invite=invite).first()


        models.guser.objects.create(  # 订单写入数据库
                job_id=form.cleaned_data['job_id'],
                username=form.cleaned_data['username'],
                gender = form.cleaned_data["gender"],
                age=form.cleaned_data["age"],
                password=form.cleaned_data["password"] ,
                bumen=form.cleaned_data["bumen"],
                mobile_phone=form.cleaned_data['mobile_phone'],
                org_id=invite_object.org_id

            )
        invite_object.number = int(invite_object.number) + 1
        invite_object.save()#更新一下邀请码的邀请次数

        request.session['user_mobile_phone'] =mobile_phone
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({"status": True, 'data': "/web/Gindex/"})

    return JsonResponse({'status': False, 'error': form.errors})



def send_sms(request):
    """ 发送短信 """
    form = SendSmsForm(request, data=request.GET)
    # 只是校验手机号：不能为空、格式是否正确
    if form.is_valid():
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """ 短信登录 """
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'web/login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)  # 确定是POST之后校验，之后
    if form.is_valid():
        # 用户输入正确，登录成功
        mobile_phone = form.cleaned_data['mobile_phone']
        if request.POST.get("options")=="dw":
            user_objectdw = models.organization.objects.filter(mobile_phone=mobile_phone).first()
            if user_objectdw:  # 没查到此人
                # 登录成功为止1
                request.session['user_mobile_phone'] = user_objectdw.mobile_phone
                request.session.set_expiry(60 * 60 * 24 * 14)

                v = models.trade.objects.filter(org_id=user_objectdw.org_id).filter(status="2").order_by(
                    "-crdate").first()

                if v:  # 查询到了有订单
                    if v.end >= datetime.datetime.now():  # 一个有没有时区一个有时区不能比较
                        return JsonResponse({"status": True, 'data': "/web/organindex/"})
                    else:
                        return JsonResponse({"status": True, 'data': "/web/price/"})
                else:  # 没买过去
                    return JsonResponse({"status": True, 'data': "/web/price/"})
            else:


                return JsonResponse({"status": False, 'error': {"mobile_phone":"此用户没有注册"}})

        elif request.POST.get("options")=="gr":
            user_objectgr = models.guser.objects.filter(mobile_phone=mobile_phone).first()
            if user_objectgr:  # 没有查到这个人
                request.session['user_mobile_phone'] = user_objectgr.mobile_phone
                request.session.set_expiry(60 * 60 * 24 * 14)

                # 关于能不能打卡的问题，在打卡提交的时候再写
                return JsonResponse({"status": True, 'data': "/web/Gindex/"})
            else:

                return JsonResponse({"status": False, 'error': {"mobile_phone": "此用户没有注册！"}})

        else:
            return JsonResponse({"status": False, 'error': {"mobile_phone": "提交参数错误！"}})



    return JsonResponse({"status": False, 'error': form.errors})






def login(request):
    """ 用户名和密码登录 """
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = LoginForm(request, data=request.POST)

    if form.is_valid():  #验证通过
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']


        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        #  (手机=username and pwd=pwd) or (邮箱=username and pwd=pwd)
        if request.POST.get("options")=="dw":
            user_objectdw = models.organization.objects.filter(mobile_phone=username).filter(
                password=password).first()
            if user_objectdw: #没查到此人
                    # 登录成功为止1
                    request.session['user_mobile_phone'] = user_objectdw.mobile_phone
                    request.session.set_expiry(60 * 60 * 24 * 14)

                    v = models.trade.objects.filter(org_id=user_objectdw.org_id).filter(status="2").order_by("-crdate").first()

                    if v:  # 查询到了有订单
                        if v.end >= datetime.datetime.now():  # 一个有没有时区一个有时区不能比较
                                return redirect('/web/organindex/')
                        else:
                                return redirect('/web/price/')
                    else:  # 没买过去
                            return redirect('/web/price/')
            else:
                form.add_error('username', '用户名或密码错误')

        elif request.POST.get("options")=="gr":
            user_objectgr = models.guser.objects.filter(mobile_phone=username).filter(password=password).first()
            if user_objectgr: #没有查到这个人
                request.session['user_mobile_phone'] = user_objectgr.mobile_phone
                request.session.set_expiry(60 * 60 * 24 * 14)

                # 关于能不能打卡的问题，在打卡提交的时候再写
                return redirect('/web/Gindex/')
            else:
                form.add_error('username', '用户名或密码错误')
        else:
            form.add_error('username', '提交的数据不合法')

    return render(request, 'web/login.html', {'form': form})



def image_code(request):
    """ 生成图片验证码 """

    image_object, code = check_code()
    print("图片验证码是:", code)
    request.session['image_code'] = code  # 将code写到session中
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s

    stream = BytesIO()
    image_object.save(stream, 'png')  # 图片写到内存中
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('/web/index/')


